<template>
  <div>
    <el-button type="text" @click="open">授权的小区详情</el-button>
    <el-button
      type="primary"
      icon="el-icon-search"
      @click="handleAdd"
      size="mini"
      >授权新小区</el-button
    >

    <!-- 拟态框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      @close="closeDialog"
    >
      <el-form
        :model="cell"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        style="width: 600px"
      >
        <el-form-item label="小区名字" prop="cname">
          <el-input v-model="cell.cname" placeholder="小区名字"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="cell.address" placeholder="地址"></el-input>
        </el-form-item>
        <el-form-item label="小区负责人" prop="duty">
          <el-input v-model="cell.duty" placeholder="小区负责人"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="tel">
          <el-input v-model="cell.tel" placeholder="联系方式"></el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="ending">
          <el-date-picker
            v-model="cell.ending"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="有效期"
            width="200"
          >
          </el-date-picker>
        </el-form-item>
        <!-- v-if="dialogTitle == '授权小区'" -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="modifyCell('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 主表格 -->
    <el-table :data="pageBean.beanList" border style="width: 100%">
      <!-- @selection-change="handleSelectionChange" -->
      <!-- <el-table-column fixed type="selection" width="55"></el-table-column> -->
      <el-table-column fixed prop="cname" label="小区名称" width="120">
      </el-table-column>
      <el-table-column prop="address" label="地址" width="210">
      </el-table-column>
      <el-table-column prop="duty" label="负责人" width="210">
      </el-table-column>
      <el-table-column prop="tel" label="联系电话" width="210">
      </el-table-column>
      <el-table-column prop="ending" label="到期时间" width="210">
      </el-table-column>
      <!-- <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)" type="text" size="small"
              >编辑</el-button
            >
            <el-button @click="handleDelete(scope.row)" type="text" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column> -->
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="handleEdit(scope.row, scope.$index)"
            circle
            size="mini"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            size="mini"
            @click="handleDelete(scope.row, scope.$index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页插件 -->
    <template>
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-sizes="[3, 5, 8]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageBean.totalRecord"
        >
        </el-pagination>
      </div>
    </template>
  </div>
</template>

<script>
export default {
  data() {
    var checkTel = (rule, value, callback) => {
      if (value == "" || value == undefined) {
        callback(new Error("输入手机号码"));
      } else if (!/^1[3456789][0-9]\d{8}$/.test(value)) {
        callback(new Error("号码格式错误"));
      }
    };
    return {
      pageIndex: 1,
      pageSize: 5,
      pageBean: {},
      cell: {},
      dialogFormVisible: false,
      dialogTitle: "",
      multipleSelection: [],

      //前端校验规则
      rules: {
        cname: [
          {
            required: true,
            message: "请输入小区名字",
            trigger: ["change", "blur"],
          },
        ],
        address: [
          {
            required: true,
            message: "请输入小区所在地",
            trigger: ["change", "blur"],
          },
        ],
        duty: [
          {
            required: true,
            message: "请输入负责人",
            trigger: ["change", "blur"],
          },
        ],
        ending: [
          {
            required: true,
            message: "请输入授权到期时间",
            trigger: ["change", "blur"],
          },
        ],
        tel: [
          { required: true, message: "请输入负责人联系方式" },
          { validator: checkTel, trigger: ["change", "blur"] },
        ],
      },
    };
  },
  methods: {
    closeDialog() {
      this.$refs.ruleForm.resetFields();
      this.cell = {};
    },
    close(formName) {
      this.$refs[formName].clearValidate();
      this.dialogFormVisible = false;
    },
    //多选按钮事件改变时调用
    handleSelectionChange(row) {
      this.multipleSelection = row;
    },
    handleSizeChange(size) {
      //console.log(`每页 ${val} 条`);
      this.pageSize = size;
      this.queryCell();
    },
    handleCurrentChange(page) {
      //console.log(`当前页: ${page}`);
      this.pageIndex = page;
      this.queryCell();
    },
    queryCell() {
      this.$axios
        .post(
          "/cell/selectCell/" + this.pageIndex + "/" + this.pageSize,
          this.pageBean
        )
        .then((res) => {
          if (res.data.code == 200) {
            this.pageBean = res.data.data;
          }
        });
    },
    handleEdit(row, index) {
      this.dialogFormVisible = true;
      this.dialogTitle = "修改小区";
      this.cell = { ...row };
    },
    handleAdd() {
      this.dialogFormVisible = true;
      this.dialogTitle = "授权新小区";
      this.cell = {};
    },
    modifyCell(formName) {
      if (this.dialogTitle == "修改小区") {
        this.$axios.post("/cell/modify", this.cell).then((res) => {
          if (res.data.code == 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            //this.getEmployeeByEid();
            console.log("cell:" + JSON.stringify(this.cell));
            this.queryCell();
            this.dialogFormVisible = false;
          } else {
            this.$message.error(res.data.msg);
          }
        });

        //验证方法
        // this.$refs[formName].validate((valid) => {
        //   //将refs中的数据放入validate校验器中验证，（valid）为一个回调函数
        //   //验证成功则发送请求传递给后端
        //   if (valid) {
        //     this.$axios.post("/cell/add", this.cell).then((res) => {

        //         if (res.data.code == 200) {
        //           this.$message({
        //             message: "修改成功",
        //             type: "success",
        //           });
        //           //this.getEmployeeByEid();
        //           console.log("cell:" + JSON.stringify(this.cell));
        //           this.cell = {};
        //           this.dialogFormVisible = false;
        //         } else {
        //           this.$message.error(res.data.msg);
        //         }
        //       });
        //   }
        // });
      } else {
        //this.dialogTitle = "创建员工";
        //this.$refs[formName].validate((valid) => {
        ////将refs中的数据放入validate校验器中验证，（valid）为一个回调函数
        ////验证成功则发送请求传递给后端
        //   if (valid) {
        //     if (this.dialogTitle == "修改小区") {
        //       this.$axios
        //         .post("/cell/modify", this.cell)
        //         .then((res) => {
        //           if (res.data.code == 200) {
        //             this.$message({
        //               message: "添加成功",
        //               type: "success",
        //             });
        //             //location.href = "/employeeList";

        //             this.dialogFormVisible = false;
        //           } else if (res.data.data) {
        //             this.$message(JSON.stringify(res.data.msg));
        //           }
        //         });
        //     }
        //   } else {
        //     console.log("前端验证失败");
        //     return false;
        //   }
        // });
        if (this.dialogTitle == "授权新小区") {
          this.$axios.post("/cell/add", this.cell).then((res) => {
            if (res.data.code == 200) {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              //location.href = "/employeeList";
              this.dialogFormVisible = false;
              this.queryCell();
            } else if (res.data.data) {
              this.$message(JSON.stringify(res.data.msg));
            }
          });
        }
      }
    },
    handleDelete(row) {
      console.log(row.cid);
      this.$confirm("此操作将此操作将失去维护的小区, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios.delete("/cell/remove/" + row.cid).then((res) => {
            if (res.data.code == 200) {
              this.$message({
                message: "删除成功！",
                type: "success",
              });
              this.queryCell();
            }
            if (res.data.code == 500) {
              this.$message.error(res.data.msg + "删除失败！");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    open() {
      this.$prompt("请输入小区名", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        // inputErrorMessage: '邮箱格式不正确'
      })
        .then(({ value }) => {
          this.$axios.get("/cell/getCellByName/" + value).then((res) => {
            if (res.data.code == 200) {
              this.$router.push("/cellshow/" + value);
              this.$message({
                type: "success",
                message: "展示的当前小区是: " + value
              });
            } else {
              this.$message({
                type: "error",
                message: res.data.msg,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
  },

  mounted() {
    this.queryCell();
  },
};
</script>

<style>
</style>